#include "StoreIOManager.h"
#include "ui_StoreIOManager.h"

StoreIOManager::StoreIOManager(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::StoreIOManager)
{
    StoreIOManager::initMenu();
}

StoreIOManager::StoreIOManager(const User &userInfo, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::StoreIOManager),m_operatorUserInfo(userInfo)
{
    StoreIOManager::initMenu();
}

void StoreIOManager::initMenu(void)
{
    ui->setupUi(this);

    m_DBManager = DatabaseManager::getInstance();
    try{
        m_DBManager->initDatabase();
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,"数据库连接初始化提示",e.what());
    }

    ui->lb_operatorName->setText(m_operatorUserInfo.getName());
    ui->lb_operatorRole->setText(reRoleMap[m_operatorUserInfo.getRole()]);
    ui->lb_operatorRole->setWordWrap(true);

    connect(ui->tbtn_exit,&QPushButton::clicked,this,&StoreIOManager::close);

    connect(ui->tbtn_IOManage,&QToolButton::clicked,this,[this]()
            {
                ui->stackedWidget->setCurrentWidget(ui->page_IOManage);
            });

    connect(ui->tbtn_recordManage,&QToolButton::clicked,this,[this]()
            {
                ui->stackedWidget->setCurrentWidget(ui->page_recordManage);
            });
    ui->stackedWidget->setCurrentWidget(ui->page_IOManage);

    StoreIOManager::initIOManagePageMenu();
    StoreIOManager::initRecordManagePageMenu();
}


StoreIOManager::~StoreIOManager()
{
    delete ui;
}

void StoreIOManager::initIOManagePageMenu()
{
    m_partInfoSqlQueryModel = new QSqlQueryModel(this);
    ui->IOManage_tv_partInfoList->setModel(m_partInfoSqlQueryModel);

    connect(ui->IOManage_tv_partInfoList,&QTableView::clicked,this,&StoreIOManager::m_on_IOManage_tv_partInfoList_clicked);
    connect(ui->IOManage_btn_refresh,&QPushButton::clicked,this,&StoreIOManager::m_on_IOManage_btn_refresh_clicked);
    connect(ui->IOManage_btn_yes,&QPushButton::clicked,this,&StoreIOManager::m_on_IOManage_btn_yes_clicked);

    StoreIOManager::m_on_IOManage_btn_refresh_clicked();
    m_partInfoSqlQueryModel->setHeaderData(0,Qt::Horizontal,tr("ID"));
    m_partInfoSqlQueryModel->setHeaderData(1,Qt::Horizontal,tr("配件名称"));
    m_partInfoSqlQueryModel->setHeaderData(2,Qt::Horizontal,tr("配件型号"));
    m_partInfoSqlQueryModel->setHeaderData(3,Qt::Horizontal,tr("价格"));
    m_partInfoSqlQueryModel->setHeaderData(4,Qt::Horizontal,tr("位置"));
    m_partInfoSqlQueryModel->setHeaderData(5,Qt::Horizontal,tr("库存数量"));
    m_partInfoSqlQueryModel->setHeaderData(6,Qt::Horizontal,tr("库存上限"));
    m_partInfoSqlQueryModel->setHeaderData(7,Qt::Horizontal,tr("库存下限"));

    ui->IOManage_tv_partInfoList->setSelectionBehavior(QAbstractItemView::SelectRows); // 单击选中整行
    ui->IOManage_tv_partInfoList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//宽度自动伸展
    ui->IOManage_tv_partInfoList->verticalHeader()->setVisible(false);//不显示行号

}

void StoreIOManager::initRecordManagePageMenu()
{
    m_outRecordInfoSqlQueryModel = new StoreIORecordManagerSqlQueryModel(this);
    ui->recordManage_tv_outRecordList->setModel(m_outRecordInfoSqlQueryModel);
    m_inRecordInfoSqlQueryModel = new StoreIORecordManagerSqlQueryModel(this);
    ui->recordManage_tv_inRecordList->setModel(m_inRecordInfoSqlQueryModel);
    connect(ui->recordManage_btn_refresh,&QPushButton::clicked,this,&StoreIOManager::m_on_record_btn_refresh_clicked);

    StoreIOManager::m_on_record_btn_refresh_clicked();

    m_outRecordInfoSqlQueryModel->setHeaderData(0,Qt::Horizontal,tr("ID"));
    m_outRecordInfoSqlQueryModel->setHeaderData(1,Qt::Horizontal,tr("配件ID"));
    m_outRecordInfoSqlQueryModel->setHeaderData(2,Qt::Horizontal,tr("操作时间"));
    m_outRecordInfoSqlQueryModel->setHeaderData(3,Qt::Horizontal,tr("状态"));
    m_outRecordInfoSqlQueryModel->setHeaderData(4,Qt::Horizontal,tr("出库数量"));

    m_inRecordInfoSqlQueryModel->setHeaderData(0,Qt::Horizontal,tr("ID"));
    m_inRecordInfoSqlQueryModel->setHeaderData(1,Qt::Horizontal,tr("配件ID"));
    m_inRecordInfoSqlQueryModel->setHeaderData(2,Qt::Horizontal,tr("操作时间"));
    m_inRecordInfoSqlQueryModel->setHeaderData(3,Qt::Horizontal,tr("状态"));
    m_inRecordInfoSqlQueryModel->setHeaderData(4,Qt::Horizontal,tr("入库数量"));

    ui->recordManage_tv_outRecordList->setSelectionBehavior(QAbstractItemView::SelectRows); // 单击选中整行
    ui->recordManage_tv_outRecordList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//宽度自动伸展
    ui->recordManage_tv_outRecordList->verticalHeader()->setVisible(false);//不显示行号

    ui->recordManage_tv_inRecordList->setSelectionBehavior(QAbstractItemView::SelectRows); // 单击选中整行
    ui->recordManage_tv_inRecordList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//宽度自动伸展
    ui->recordManage_tv_inRecordList->verticalHeader()->setVisible(false);//不显示行号
}

void StoreIOManager::mouseReleaseEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_selectPartInfoFlag = false;

        ui->IOManage_le_selectId->clear();
        ui->IOManage_le_IONumber->clear();
    }
    QWidget::mouseReleaseEvent(event);

    qDebug() << "鼠标松开事件，是否选中数据:" << m_selectPartInfoFlag;
}

void StoreIOManager::m_on_IOManage_tv_partInfoList_clicked(const QModelIndex& index)
{
    m_selectPartInfoFlag = true;

    m_currentPartInfo = Part(m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),0)).toLongLong(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),1)).toString(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),2)).toString(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),3)).toDouble(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),4)).toString(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),5)).toInt(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),6)).toInt(),
                             m_partInfoSqlQueryModel->data(this->m_partInfoSqlQueryModel->index(index.row(),7)).toInt());

    ui->IOManage_le_selectId->setText(QString("%1").arg(m_currentPartInfo.getId()));

    qDebug() << "点击列表，是否选中数据:" << m_selectPartInfoFlag << m_currentPartInfo.getId() << m_currentPartInfo.getStockQuantity();
}

void StoreIOManager::m_on_IOManage_btn_refresh_clicked()
{
    m_selectPartInfoFlag = false;

    try{
        m_partInfoSqlQueryModel->setQuery(m_DBManager->getQueryForAll("part"));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,"刷新配件信息记录提示",e.what());
    }
}

void StoreIOManager::m_on_IOManage_btn_yes_clicked()
{
    qint64 num = ui->IOManage_le_IONumber->text().toLongLong();
    if(ui->IOManage_rbtn_inStore->isChecked())
    {
        qint64 newQuantity = num + m_currentPartInfo.getStockQuantity();
        try{
            if(newQuantity > m_currentPartInfo.getStockUpperLimit())
            {
                m_DBManager->IOManage_updateQuantityinfoRecord(m_currentPartInfo.getStockUpperLimit(), m_currentPartInfo.getId());
                m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                                                m_operatorUserInfo.getName(),
                                                                m_operatorUserInfo.getRole(),
                                                                QString("入库了%1配件:[add]%2件").arg(m_currentPartInfo.getName()).arg(num)));
                m_DBManager->RecordManage_insertInRecordInfoRecord(StoreInRecord(m_currentPartInfo.getId(),
                                                                                 QDateTime::currentDateTime(),
                                                                                 "已成功入库",
                                                                                 m_currentPartInfo.getStockUpperLimit() - m_currentPartInfo.getStockQuantity()));

                m_currentPartInfo.setLocation("未分配");
                m_currentPartInfo.setStockQuantity(newQuantity - m_currentPartInfo.getStockUpperLimit());
                qint64 tmpId = m_DBManager->partManage_insertPartInfoRecord(m_currentPartInfo);
                m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                                                m_operatorUserInfo.getName(),
                                                                m_operatorUserInfo.getRole(),
                                                                QString("添加了待分配%1配件:[add]%2件").arg(m_currentPartInfo.getName()).arg(m_currentPartInfo.getStockQuantity())));
                m_DBManager->RecordManage_insertInRecordInfoRecord(StoreInRecord(tmpId,
                                                                                 QDateTime::currentDateTime(),
                                                                                 "待分配",
                                                                                 m_currentPartInfo.getStockUpperLimit() - m_currentPartInfo.getStockQuantity()));
            }
            else
            {
                m_DBManager->IOManage_updateQuantityinfoRecord(newQuantity, m_currentPartInfo.getId());
                m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                                                m_operatorUserInfo.getName(),
                                                                m_operatorUserInfo.getRole(),
                                                                QString("入库了%1配件:[add]%2件").arg(m_currentPartInfo.getName()).arg(num)));
                m_DBManager->RecordManage_insertInRecordInfoRecord(StoreInRecord(m_currentPartInfo.getId(),
                                                                                 QDateTime::currentDateTime(),
                                                                                 "已成功入库",
                                                                                 num));
            }
        }catch(const std::exception& e)
        {
            QMessageBox::critical(this,"入库配件提示",e.what());
            return;
        }
    }
    else if(ui->IOManage_rbtn_outStore->isChecked())
    {
        qint64 newQuantity = m_currentPartInfo.getStockQuantity() - num;
        try{
            if(newQuantity < m_currentPartInfo.getStockLowerLimit())
            {
                m_DBManager->IOManage_updateQuantityinfoRecord(m_currentPartInfo.getStockLowerLimit(), m_currentPartInfo.getId());
                m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                                                m_operatorUserInfo.getName(),
                                                                m_operatorUserInfo.getRole(),
                                                                QString("出库了%1配件:[add]%2件").arg(m_currentPartInfo.getName()).arg(m_currentPartInfo.getStockQuantity() - m_currentPartInfo.getStockLowerLimit())));
                m_DBManager->RecordManage_insertOutRecordInfoRecord(StoreOutRecord(m_currentPartInfo.getId(),
                                                                                 QDateTime::currentDateTime(),
                                                                                 "已出库",
                                                                                 m_currentPartInfo.getStockQuantity() - m_currentPartInfo.getStockLowerLimit()));
                m_DBManager->RecordManage_insertOutRecordInfoRecord(StoreOutRecord(m_currentPartInfo.getId(),
                                                                                   QDateTime::currentDateTime(),
                                                                                   "出库失败,已越过库存底限",
                                                                                   num - m_currentPartInfo.getStockQuantity() + m_currentPartInfo.getStockLowerLimit()));
            }
            else
            {
                m_DBManager->IOManage_updateQuantityinfoRecord(newQuantity, m_currentPartInfo.getId());
                m_DBManager->logManage_insertLogRecord(LogEntry(QDateTime::currentDateTime(),
                                                                m_operatorUserInfo.getName(),
                                                                m_operatorUserInfo.getRole(),
                                                                QString("出库了%1配件:[add]%2件").arg(m_currentPartInfo.getName()).arg(num)));
                m_DBManager->RecordManage_insertOutRecordInfoRecord(StoreOutRecord(m_currentPartInfo.getId(),
                                                                                 QDateTime::currentDateTime(),
                                                                                 "已出库",
                                                                                 num));
            }
        }catch(const std::exception& e)
        {
            QMessageBox::critical(this,"入库配件提示",e.what());
            return;
        }
    }
    StoreIOManager::m_on_IOManage_btn_refresh_clicked();
}

void StoreIOManager::m_on_record_btn_refresh_clicked()
{
    m_selectPartInfoFlag = false;

    try{
        m_outRecordInfoSqlQueryModel->setQuery(m_DBManager->getQueryForAll("storeOutRecord"));
        m_inRecordInfoSqlQueryModel->setQuery(m_DBManager->getQueryForAll("storeInRecord"));
    }catch(const std::exception& e)
    {
        QMessageBox::critical(this,"刷新出入库信息记录提示",e.what());
    }
}

StoreIORecordManagerSqlQueryModel::StoreIORecordManagerSqlQueryModel(QObject *parent): QSqlQueryModel(parent)
{

}

QVariant StoreIORecordManagerSqlQueryModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::DisplayRole)
    {
        int column = index.column();
        if(column == 2)//日期（毫秒时间戳）
        {
            return QDateTime::fromMSecsSinceEpoch(
                       QSqlQueryModel::data(index,role).toLongLong())
                .toString("yyyy-MM-dd HH:mm:ss.zzz");
        }
        return QSqlQueryModel::data(index,role);
    }
    return QSqlQueryModel::data(index, role);
}
